package org.cem.frontend;

import static org.eclipse.rap.rwt.internal.service.ContextProvider.getApplicationContext;

import javax.security.auth.login.LoginException;

import org.cem.security.CemSecurityPlugin;
import org.cem.security.Permission;
import org.eclipse.core.databinding.observable.Realm;
import org.eclipse.jface.databinding.swt.SWTObservables;
import org.eclipse.jface.wizard.WizardDialog;
import org.eclipse.rap.rwt.application.EntryPoint;
import org.eclipse.rap.rwt.internal.lifecycle.RWTLifeCycle;
import org.eclipse.swt.SWT;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;

public class FrontendEntryPoint implements EntryPoint {

	private Display display;
	private Shell shell;
	
	@Override
	public int createUI() {
		    display = Display.getDefault();
		    shell = createShell( display );
			try {
				 CemSecurityPlugin.getLoginContext().login();
				 if (!Permission.hasPermission(CemSecurityPlugin.getLoginContext().getSubject(),
						 Permission.ELECTION_ACCESS)) {
					 CemSecurityPlugin.getLoginContext().logout();
					 return 0;
				 }
			} catch (LoginException e) {
			  Throwable cause = e.getCause();
			  if( cause != null && cause.getCause() instanceof ThreadDeath ) {
			    throw ( ThreadDeath )cause.getCause();
			  }
			}
		    Realm.runWithDefault(SWTObservables.getRealm(display), new Runnable() {
		    	
				  @SuppressWarnings("restriction")
				  public void run() {
					  shell.setLayout( new GridLayout( 1, false ) );
					  createContents( shell );
					  if( shell.getMaximized() ) {
						  shell.layout();
					  } else {
						  shell.pack();
					  }
					  shell.open();
					  if( getApplicationContext().getLifeCycleFactory().getLifeCycle() instanceof RWTLifeCycle ) {
						  while( !shell.isDisposed() ) {
							  if( !display.readAndDispatch() ) {
								  display.sleep();
							  }
						  }
						  display.dispose();
					  }
				  }
		    });
		    return 0;
		  }
	  
	protected void createContents(Composite parent) {
		WizardDialog dialog = new WizardDialog((Shell) parent, new ElectionWizard());
		dialog.create();
		dialog.open();
	}

	private Shell getShell() {
		return shell;
	}

	protected Shell createShell( Display display ) {
	    Shell shell = new Shell( display, SWT.NO_TRIM );
	    shell.setMaximized( true );
	    return shell;
	}
}
